//
//  AccountDescListViewController.m
//  quickBatchManager
//
//  Created by 王定波 on 15/10/10.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "AccountDescListViewController.h"

@interface AccountDescListViewController ()
{
    NSArray *datalist;
    AccountType accounttype;
   
}
@end

@implementation AccountDescListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    sessionControl = [[WSSessionController sharedController]init];
}

- (void)_accessoryDidDisconnect:(NSNotification *)notification{
    
    // [[self navigationController] popViewControllerAnimated:YES];
    
    if (sessionControl != nil) {
        sessionControl = nil;
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(void)initData
{
   // accounttype=AccountTypeClient;
    
    [self reloadData];
}

-(void)initUI
{
    [self addNavBack];
    UIColor *sbgColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"beijingtur"]];
    [self.view setBackgroundColor:sbgColor];
    
    UIImage *image = _bg.image;
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
    _bg.image=image;
    
    _tableView.backgroundColor=[UIColor clearColor];
    _mainView.backgroundColor=[UIColor clearColor];
    
    self.view.frame=CGRectMake(0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT);
    
    [_dzbtn bk_whenTapped:^{
        
        InOutAccountViewController *vc=[[InOutAccountViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        self.definesPresentationContext = YES;
        vc.delegate=self;
        
        vc.accountType=_accountType;
        vc.supplier=_supplier;
        vc.client=_client;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        [self presentViewController:vc animated:YES completion:nil];

       
    }];
    
    [_jsbtn bk_whenTapped:^{
        ClearPriceViewController *vc=[[ClearPriceViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        self.definesPresentationContext = YES;
        vc.delegate=self;
        vc.accountType=_accountType;
        vc.supplier=_supplier;
        vc.client=_client;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        [self presentViewController:vc animated:YES completion:nil];
    }];
//
//    [_dbbtn bk_whenTapped:^{
//        
//        
//    }];
    
    
    
    [_addBtn bk_whenTapped:^{
        NSMutableArray *navarray=[[NSMutableArray alloc] init];
        [navarray addObject:[self.splitViewController.viewControllers objectAtIndex:0] ];
        if(accounttype==AccountTypeSupplier)
        {
            
            EditSupplierViewController *handVc=[[EditSupplierViewController alloc] init];
            handVc.delegate=self;
            [navarray addObject:handVc];
        }
        else
        {
            AddClientController *handVc=[[AddClientController alloc] init];
            handVc.clientType=accounttype;
            handVc.delegate=self;
            [navarray addObject:handVc];
            self.splitViewController.viewControllers=navarray;
        }
    }];
    
    
    [_isShowPayBtn bk_whenTapped:^{
        _isShowPayBtn.selected=(!_isShowPayBtn.selected);
    }];
    
    
    
    switch (_accountType) {
        case AccountTypeSupplier:
            _titleLabel.text=[NSString stringWithFormat:@"供货商 %@ 的账目",_supplier.contactName];
            break;
        case AccountTypeClient:
        case AccountTypeAllocate:
             _titleLabel.text=[NSString stringWithFormat:@"%@ 的账目",_client.clientName];
            break;
            
        default:
            break;
    }
    
    
    [_printBtn bk_whenTapped:^{
        if(datalist && datalist.count)
        {
            [PrintUtil printBill:datalist andClient:_client andType:_accountType andControl:sessionControl];
        }
    }];
    
    [_fsbtn bk_whenTapped:^{
        [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeImage;
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:UM_KEY
                                          shareText:nil
                                         shareImage:[ToolUtils snapshot:self.mainView]
                                    shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline]
                                           delegate:nil];
    }];
    
    
}

-(void)reloadData
{
    NSMutableArray *mlist=[[NSMutableArray alloc]init];
    switch (_accountType) {
        case AccountTypeSupplier:
            [mlist addObjectsFromArray:[AppService getBatchListById:_supplier.supplierId andStartDate:nil andEndDate:nil]];
            [mlist addObjectsFromArray:[AppService getPayOutListById:_supplier.supplierId andStartDate:nil andEndDate:nil]];
            
            [mlist addObjectsFromArray:[AppService getClearPriceListBySupplierId:_supplier.supplierId andStartDate:nil andEndDate:nil]];
            
            break;
        case AccountTypeClient:
        case AccountTypeAllocate:
            [mlist addObjectsFromArray:[AppService getPayInListById:_client.clientId andStartDate:nil andEndDate:nil]];
            [mlist addObjectsFromArray:[AppService getClearPriceListByClientId:_client.clientId andStartDate:nil andEndDate:nil]];
            [mlist addObjectsFromArray:[AppService getOrderListById:_client.clientId andStartDate:nil andEndDate:nil]];
            
            break;
        default:
            break;
    }
    
    for (int i=0; i<mlist.count; i++) {
        if(_accountType== AccountTypeSupplier)
        {
            float totalPrice = 0.0;
            float moneyReceipt = 0.0;
             for (int i=0; i<mlist.count; i++) {
                   NSObject *obj = [mlist objectAtIndex:i];
                 if([obj isKindOfClass:[PayOutModel class]])
                 {
                     PayOutModel *outModel = (PayOutModel *)obj;
                     moneyReceipt= moneyReceipt+outModel.amount;
                 }
                 if([obj isKindOfClass:[BatchProductModel class]])
                 {
                     BatchProductModel *batchModel = (BatchProductModel *)obj;
                     totalPrice = totalPrice+batchModel.totalPrice;
                 }
             }
            [_tipLabel setText:[NSString stringWithFormat:@"金额 :%0.2f - 已支付:%0.2f",totalPrice,moneyReceipt]];
            
        }
        
        if(_accountType== AccountTypeAllocate || _accountType==AccountTypeClient)
        {
            float totalPrice = 0.0;
            float moneyReceipt = 0.0;
            for (int i=0; i<mlist.count; i++) {
                NSObject *obj = [mlist objectAtIndex:i];
                if([obj isKindOfClass:[PayInModel class]])
                {
                    PayInModel *inModel = (PayInModel *)obj;
                    moneyReceipt= moneyReceipt+inModel.amount;
                }
                
                if([obj isKindOfClass:[SaleOrderModel class]])
                {
                    SaleOrderModel *orderModel = (SaleOrderModel *)obj;
                    if(orderModel.isPay)
                        moneyReceipt = moneyReceipt+orderModel.paidPrice;
                    totalPrice = totalPrice + orderModel.totalPrice;
                }
            }
            
            [_tipLabel setText:[NSString stringWithFormat:@"总金额 :%0.2f - 已收款:%0.2f - 余款:%0.2f",totalPrice,moneyReceipt,totalPrice-moneyReceipt]];
        }
       
    }
    
    
    datalist=[mlist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id  obj2) {
        NSString *date1,*date2;
        
        if([obj1 isKindOfClass:[ClearPriceModel class]])
        {
            date1=((ClearPriceModel*)obj1).clearDate;
        }
        
        if([obj2 isKindOfClass:[ClearPriceModel class]])
        {
            date2=((ClearPriceModel*)obj2).clearDate;
        }
        
        
        if([obj1 isKindOfClass:[BatchProductModel class]])
        {
            date1=((BatchProductModel*)obj1).createDate;
        }
        
        if([obj2 isKindOfClass:[BatchProductModel class]])
        {
            date2=((BatchProductModel*)obj2).createDate;
        }
        
        
        
        if([obj1 isKindOfClass:[PayOutModel class]])
        {
            date1=((PayOutModel*)obj1).payDate;
        }
        
        if([obj2 isKindOfClass:[PayOutModel class]])
        {
            date2=((PayOutModel*)obj2).payDate;
        }
        
        if([obj1 isKindOfClass:[PayInModel class]])
        {
            date1=((PayInModel*)obj1).payDate;
        }
        
        if([obj2 isKindOfClass:[PayInModel class]])
        {
            date2=((PayInModel*)obj2).payDate;
        }
        
        
        if([obj1 isKindOfClass:[SaleOrderModel class]])
        {
            date1=((SaleOrderModel*)obj1).date;
        }
        
        if([obj2 isKindOfClass:[SaleOrderModel class]])
        {
            date2=((SaleOrderModel*)obj2).date;
        }

        
        
         return [date1 compare:date2];
    }];
    
    
    
    [_tableView reloadData];
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return datalist.count;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
     id data=[datalist objectAtIndex:indexPath.row];
    
    if([data isKindOfClass:[PayInModel class]])
    {
        InOutAccountViewController *vc=[[InOutAccountViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        self.definesPresentationContext = YES;
        vc.delegate=self;
        
        vc.accountType=_accountType;
        vc.supplier=_supplier;
        vc.client=_client;
        vc.payin=data;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        [self presentViewController:vc animated:YES completion:nil];
    }
    else if([data isKindOfClass:[PayOutModel class]])
    {
        InOutAccountViewController *vc=[[InOutAccountViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        self.definesPresentationContext = YES;
        vc.delegate=self;
        
        vc.accountType=_accountType;
        vc.supplier=_supplier;
        vc.client=_client;
        vc.payout=data;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        [self presentViewController:vc animated:YES completion:nil];
    }
    else if ([data isKindOfClass:[BatchProductModel class]] || [data isKindOfClass:[SaleOrderModel class]])
    {
        AccountDescViewController *vc=[[AccountDescViewController alloc] init];
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        self.definesPresentationContext = YES;
        vc.orderData=data;
        vc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        [self presentViewController:vc animated:YES completion:nil];
    }
    
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    id data=[datalist objectAtIndex:indexPath.row];
    
    
    if([data isKindOfClass:[ClearPriceModel class]])
    {
        NSString *reuseIdetify = @"ClearPriceViewCell";
        ClearPriceViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
        if(!cell){
            
            
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"ClearPriceViewCell" owner:self options:nil];
            for(id oneObject in nib){
                if([oneObject isKindOfClass:[ClearPriceViewCell class]]){
                    cell = (ClearPriceViewCell *) oneObject;
                    
                }
            }
            
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.backgroundColor=[UIColor clearColor];
        
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
            
        }
        if ([cell respondsToSelector:@selector(setLayoutMargins:)])  {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        
        [cell setData:data];
        return cell;
    }
    else
    {
        NSString *reuseIdetify = @"AccountDescListViewCell";
        AccountDescListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
        if(!cell){
            
            
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"AccountDescListViewCell" owner:self options:nil];
            for(id oneObject in nib){
                if([oneObject isKindOfClass:[AccountDescListViewCell class]]){
                    cell = (AccountDescListViewCell *) oneObject;
                    
                }
            }
            
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.backgroundColor=[UIColor clearColor];
        
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
            
        }
        if ([cell respondsToSelector:@selector(setLayoutMargins:)])  {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        
        [cell setAccountData:data];
        return cell;
    }
  
    
    
}


-(void)didChange:(ChangeType)type andData:(id)data
{
    [self reloadData];
}


@end
